﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Management.Automation;

namespace BO.Management.PowerShell.Provider
{
    public class BusinessObjectDriveInfo : PSDriveInfo
    {
        public BusinessObjectDriveInfo(PSDriveInfo driveInfo, BusinessObjectDriveParameters parameters)
            : base(driveInfo)
        {
            this.LogonProvider = new LogonProvider();
            if (parameters == null) return;

            CrystalDecisions.Enterprise.EnterpriseSession session = this.GetSession(parameters);
            if (session == null)
            {
                throw new Exception("Unable to get connection to the BOE infrastructure");
            }
        }

        public LogonProvider LogonProvider { get; set; }

        public CrystalDecisions.Enterprise.EnterpriseSession Session { get; set; }

        /// <summary>
        /// Get a BO session to use management powershell.
        /// </summary>
        /// <returns></returns>
        internal CrystalDecisions.Enterprise.EnterpriseSession GetSession(BusinessObjectDriveParameters parameters)
        {
            if (this.Session != null)
            {
                return this.Session;
            }

            if (!String.IsNullOrEmpty(parameters.SessionToken))
            {
                return this.LogonProvider.LogonWithToken(parameters.SessionToken);
            }

            if (!String.IsNullOrEmpty(parameters.UserName) && !String.IsNullOrEmpty(parameters.CmsName))
            {
                return this.LogonProvider.Logon(parameters.UserName, parameters.Password, parameters.CmsName);
            }
            else
            {
                return this.LogonProvider.Logon(parameters.CmsName);
            }
        }


    }
}
